package com.llxwz.event;

import com.alibaba.fastjson.JSONObject;
import com.llxwz.entity.Event;
import com.llxwz.entity.Message;
import com.llxwz.service.MessageService;
import com.llxwz.util.CommunityConstant;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.llxwz.util.CommunityConstant.*;

// bindings其实就是用来确定队列和交换机绑定关系
@RabbitListener(queues = {QUEUE_COMMENT,QUEUE_LIKE,QUEUE_FOLLOW})
@Component
public class EventConsumer implements CommunityConstant {


    @Autowired
    private MessageService messageService;

    @RabbitHandler
    public void handleCommentMessage(String record) {

        if (record == null || "".equals(record)) {
            System.out.println("消息的内容为空!");
            return;
        }

        Event event = JSONObject.parseObject(record, Event.class);
        if (event == null) {
            System.out.println("消息格式错误!");
            return;
        }

        // 发送站内通知
        Message message = new Message();
        message.setFromId(SYSTEM_USER_ID);
        message.setToId(event.getEntityUserId());
        message.setConversationId(event.getRouteName());
        message.setCreateTime(new Date());

        Map<String, Object> content = new HashMap<>();
        content.put("userId", event.getUserId());
        content.put("entityType", event.getEntityType());
        content.put("entityId", event.getEntityId());

        if (!event.getData().isEmpty()) {
            for (Map.Entry<String, Object> entry : event.getData().entrySet()) {
                content.put(entry.getKey(), entry.getValue());
            }
        }

        message.setContent(JSONObject.toJSONString(content));
        messageService.addMessage(message);
    }
}